package com.xusheng.cli.core.config;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.xusheng.cli.other.StringToEnumConverterFactory;
import com.xusheng.cli.tools.StpPlayerUtil;
import com.xusheng.cli.tools.StpProxyUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author jy
 * @since 2021-11-08 15:32
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    // 注册Sa-Token的注解拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器，并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
        // 注册Sa-Token的路由拦截器
		/*registry.addInterceptor(new SaRouteInterceptor())
				.addPathPatterns("/**")
				.excludePathPatterns("/api/v1/login/login", "/api/v1/account/verificationCode");*/

        registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
            SaRouter.match("/api/v1/**")
                    .notMatch("/api/v1/login/login", "/api/v1/account/verificationCode", "/api/v1/fakapay/paynotify")
                    .check(r -> StpUtil.checkLogin());
            SaRouter.match("/user/v1/**")
                    .check(r -> StpPlayerUtil.checkLogin());
            SaRouter.match("/proxy/v1/**")
                    .notMatch("/proxy/v1/login/login", "/proxy/v1/login/verificationCode")
                    .check(r -> StpProxyUtil.checkLogin());
        })).addPathPatterns("/**");
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new StringToEnumConverterFactory());
    }

}
